import { defineEventHandler, getCookie, getQuery, createError } from 'h3';
import { BackupManager } from '../../utils/backup.js';
import fs from 'fs/promises';
import path from 'node:path';

export default defineEventHandler(async (event) => {
  try {
    const userId = getCookie(event, 'userId');
    if (!userId) {
      throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
    }

    const { filename } = getQuery(event);
    if (!filename) {
      throw createError({ statusCode: 400, statusMessage: 'Filename is required' });
    }

    const backupManager = new BackupManager();
    const backupPath = path.join(backupManager.backupDir, filename);
    
    // 验证备份文件存在
    try {
      await fs.access(backupPath);
    } catch {
      throw createError({ statusCode: 404, statusMessage: 'Backup file not found' });
    }

    // 设置响应头
    setHeader(event, 'Content-Type', 'application/octet-stream');
    setHeader(event, 'Content-Disposition', `attachment; filename="${filename}"`);
    
    // 读取并返回文件
    const fileBuffer = await fs.readFile(backupPath);
    return fileBuffer;
  } catch (error) {
    console.error('下载备份失败:', error);
    if (error.statusCode) {
      throw error;
    }
    throw createError({ statusCode: 500, statusMessage: 'Failed to download backup' });
  }
});
